<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPerm('addEmployee')" size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employessList">
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" width="200px">
            <template v-slot="obj">
              <img v-fiximg class="avatar" :src="obj.row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号码" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">

            <template v-slot="obj">
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="0"
                :disabled="true"
              />
            </template>

          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="obj">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRole(obj.row.id)">设置角色</el-button>
              <el-button type="text" size="small" @click="delEmployees(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :size-change="pageConfig.size"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployees :is-show-dialog="isShowDialog" />
      <AssignaRole
        ref="assignRole"
        :is-show-dialog="isShowRole"
        @closeRoleDialog="isShowRole = false"
      />
    </div>
  </div>
</template>

<script>
import { getEmployess, delEmployees } from '@/api/employees'
import employeesEmui from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployees from './components/add-employee.vue'
import AssignaRole from './components/assign-role'
export default {
  components: { AddEmployees, AssignaRole },
  data() {
    return {
      employessList: [],
      pageConfig: {
        page: 1,
        size: 5
      },
      total: 0,
      isShowDialog: false,
      isShowRole: false
    }
  },
  async created() {
    this.loadPage()
  },
  methods: {
    // 判断按钮权限的函数
    // checkPerm(pointName) {
    //   // 传入一个按钮权限名, 可以返回这个权限是否存在于个人数据中的布尔值
    //   const points = this.$store.state.user.userInfo.roles.points
    //   return points.includes(pointName)
    // },

    async assignRole(userId) {
      await this.$refs.assignRole.getUserRoles(userId)
      this.isShowRole = true
    },
    async delEmployees(id) {
      try {
        // 二次确认
        await this.$confirm(this.$t('delCoim'))
        // 发起请求
        await delEmployees(id)
        // 提示
        this.$message.success('删除成功')
        // 更新页面
        this.loadPage()
      } catch (error) {
        console.log(error)
      }
    },
    async exportExcel() {
      // 导出 excel 功能
      // 1. 获取到所有数据
      // const { rows } = await getEmployee({ page: 1, size: 999 })
      // console.log(rows)
      // 2.生成一个 excel 文件
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     ['张三', '19', '男'],
      //     ['小明', '20', '男'],
      //     ['李四', '14', '女']
      //   ]
      // })
      const { rows } = await getEmployess({ page: 1, size: 999 })
      const zidian = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const header = Object.keys(zidian)

      const data = rows.map(objUser => {
        const arrUser = []
        for (const zhkey in zidian) {
          // zhKey 假设遍历到姓名
          // console.log(zhkey)
          const enKey = zidian[zhkey] // username
          const value = objUser[enKey] // 王大锤
          // arrUser.push(value)
          if (enKey === 'formOfEmployment') {
            const res = employeesEmui.hireType.find(el => el.id === value)
            arrUser.push(res ? res.value : '')
          } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            arrUser.push(formatDate(value))
          } else {
            arrUser.push(value) // 王大锤
          }
        }
        return arrUser
      })
      console.log(data)
      export_json_to_excel({
        header,
        data
      })
    },
    async loadPage() {
      const { total, rows } = await getEmployess(this.pageConfig)
      this.total = total
      this.employessList = rows
    },
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.loadPage()
    },
    formatEmployment(row, col, cellVal) {
      const res = employeesEmui.hireType.find(el => el.id === cellVal)
      return res ? res.value : ''
    }
  }
}
</script>

<style lang="scss" scoped>
  .avatar {
    width: 180px;
    height: 88px;

    // 有个 css 可以控制图片宽高比
  // 两个常用选项 cover 是在保持宽高比的情况下覆盖全部内容
  // contain 是在保持宽高比的情况下, 尽可能显示全部图片
    object-fit: cover;
  }
</style>
